<template>
    <Div>
        <Card dis-hover >
            <h3>
              当前任务：{{taskInfo.taskName}}
            </h3>
            <ButtonGroup slot="extra"  v-if="!taskInfo.viewFlag">
                <Button @click="submitAndUpdate('showdata')" type="warning" style="background: #EF5350;" :loading="buttonloading1"  v-if="taskInfo.procinstState === '2'">
                    <Icon type="ios-bookmark" />
                    审批
                </Button>
                <Button type="warning" style="background: #EF5350;" :loading="buttonloading1" @click="submit('showdata')" v-else>
                    <Icon type="ios-bookmark" />
                    审批
                </Button>
                <Button @click="returnTo">
                    返回
                    <Icon type="ios-arrow-forward" />
                </Button>
            </ButtonGroup>
            <ButtonGroup slot="extra"  v-else>
                <Button @click="returnTo">
                    返回
                    <Icon type="ios-arrow-forward" />
                </Button>
            </ButtonGroup>
        </Card>
        <Card dis-hover style="margin: 10px;">
            <div :style="{ overflowY: 'auto'}" v-if="taskInfo.procinstState === '2'"  >
                <Col span="18">
                    <Form  :model="showdata"  ref="showdata" :rules="ruleCustom1" :label-width="160">
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11" >
                                <FormItem label="活动方案名称：" prop="programmeName">
                                    <Input type="text" v-model="showdata.programmeName"></Input>
                                </FormItem>
                            </Col>
                            <Col span="11" >
                                <FormItem label="活动主题：" prop="themeName">
                                    <Input type="text" v-model="showdata.themeName"></Input>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11" >
                                <FormItem label="开始时间：" prop="startDate">
                                    <DatePicker v-model="showdata.startDate" type="date" style="width: 100%;"
                                                placeholder="请输入"></DatePicker>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label="结束时间：" prop="endDate">
                                    <DatePicker v-model="showdata.endDate" type="date"  style="width: 100%;"
                                                placeholder="请输入"></DatePicker>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label="负责人：" prop="possess">
                                    <Input type="text" v-model="showdata.possess"></Input>
                                </FormItem>
                            </Col>
                            <Col span="11" >
                                <FormItem label="联系方式：" prop="phone">
                                    <Input type="text" v-model="showdata.phone"></Input>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label="主办单位：" prop="themeAddress">
                                    <Input v-model="showdata.themeAddress" type="text"/>
                                </FormItem>
                            </Col>

                            <Col span="11" >
                                <FormItem label="编制人员：" prop="staffName">
                                    {{showdata.staffName}}
                                </FormItem>
                            </Col>

                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">

                                <FormItem label="审核人员：" prop="auditorName">
                                    {{showdata.auditorName}}
                                </FormItem>

                            </Col>
                            <Col span="11" >

                                <FormItem label="批准人员：" prop="approvedByName">
                                    {{showdata.approvedByName}}
                                </FormItem>

                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23" >
                                <FormItem label="描述：" prop="desc">
                                    <Input v-model="showdata.desc" type="textarea" :rows="2"/>
                                </FormItem>
                            </Col>
                        </Row>

                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label="方案附件：" prop="whetherVote">
                                    <Upload
                                            ref="upload"
                                            type="drag"
                                            :show-upload-list="true"
                                            :before-upload="beforeUpload"
                                            :action="upUrl"
                                            :max-size="1024000"
                                    >
                                        <div style="padding: 0px 0;height: 70px">
                                            <Icon type="ios-cloud-upload" size="40" style="color: #3399ff"></Icon>
                                            <p> 请上传大小不超过5MB的文件</p>
                                        </div>
                                    </Upload>
                                    <div v-if="fileName !== null">
                                        附件： <a @click.prevent="downloadFile(fileId,fileName)">{{fileName}}</a>
                                        <Button type="text" icon="md-trash"
                                                @click="deleteFile(showdata.programmeFile)"
                                                style="margin-left: 20px;margin-bottom: 3px"/>
                                    </div>
                                </FormItem>
                            </Col>
                        </Row>

                    </Form>
                </Col>
            </div>
            <div :style="{ overflowY: 'auto'}"  v-else>
                <Col span="24">
                    <Form  :model="showdata"  ref="showdata" :rules="ruleCustom" :label-width="160">
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11" >
                                <FormItem label="活动方案名称：" prop="programmeName">
                                    {{showdata.programmeName}}
                                </FormItem>
                            </Col>
                            <Col span="11" >
                                <FormItem label="编制日期：" prop="preparationDate" >
                                    {{ formatDate(new Date(showdata.preparationDate), 'yyyy-MM-dd')}}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label="活动主题：" prop="themeName">
                                    {{showdata.themeName}}
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label="负责人：" prop="possess">
                                    {{showdata.possess}}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label="联系方式：" prop="phone">
                                    {{showdata.phone}}
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label="主办单位：" prop="themeAddress">
                                    {{showdata.themeAddress}}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label="开始时间：" prop="startDate">
                                    {{formatDate(new Date(showdata.startDate), 'yyyy-MM-dd')}}
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label="结束时间：" prop="endDate">
                                    {{formatDate(new Date(showdata.endDate), 'yyyy-MM-dd')}}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11" >
                                <FormItem label="编制人员：" prop="staffName">
                                    {{showdata.staffName}}
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label="审核人员：" prop="auditorName">
                                    {{showdata.auditorName}}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label="批准人员：" prop="approvedByName">
                                    {{showdata.approvedByName}}
                                </FormItem>
                            </Col>
                            <Col span="11" >
                                <FormItem label="上报单位：" prop="whetherComments">
                                    {{showdata.orgName}}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label="上报日期：" prop="reportingDate">
                                    {{ formatDate(new Date(showdata.reportingDate), 'yyyy-MM-dd')}}
                                </FormItem>
                            </Col>
                            <Col span="11" >
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label="描述：" prop="desc">
                                    {{showdata.desc}}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label="方案附件：" prop="programmeFile">
                                    <a @click.prevent="downloadFile(fileId,fileName)">{{fileName}}</a>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row v-if="!taskInfo.viewFlag">
                            <Col span="11">
                                <FormItem label="审批结果：" prop="route">
                                    <Select  v-model="showdata.route" @on-change="routePush"  >
                                        <Option v-for="item in approveList" :value="item.value" :key="item.value">{{ item.text }}</Option>
                                    </Select>
                                </FormItem>
                            </Col>

                        </Row>
                        <Row v-if="!taskInfo.viewFlag">
                            <Col span="11">
                                <FormItem label="处理意见：" prop="opinion">
                                    <Input v-model="showdata.opinion" type="textarea" :rows="2" />
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                </Col>

            </div >

        </Card>
    </Div>
</template>


<script>
	import {Api} from '../../../../api/index.js'
    import { sessionStorage, cookie } from '../../../../common/cacheUtils.js'
    import cascaderDom from "../../../../components/cascader-dom.vue"
	export default {
        components: {
            cascaderDom
        },
		data() {
			return {
                user:{},
                buttonloading1:false,
                upUrl: Api.uploadMongoFile,
                approveList : [
                    {
                        text:"通过",
                        value:"1"
                    },
                    {
                        text:"不通过",
                        value:"2"
                    }
                ],
                buttonloading: false,
                viewFlag : false,
                flag : false,
                approveFlag : '',
                showdata: {},
                tableHeight : 450,
                file : null,
                fileName : null,
                downloadUrl : Api.downloadMongoFile,
                formList : [],
                 ruleCustom : {
                    opinion: [
                        { required: true, message: '  ', trigger: 'blur' }
                    ],
                    route: [
                        { required: true, message: '  ', trigger: 'blur' }
                    ]
                 },
                ruleCustom1: {
                    programmeName: [{
                        required: true,
                        message: '  ',
                        trigger: 'blur'
                    }],
                    possess: [{
                        required: true,
                        message: '  ',
                        trigger: 'blur'
                    }],
                    themeName: [{
                        required: true,
                        message: '  ',
                        trigger: 'blur'
                    }],
                    phone: [{
                        validator: (rule, value, callback) => {
                            if (!(/^1[3456789]\d{9}$/.test(value))) {
                                callback(' ');

                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'change'
                    }],
                    startDate: [{
                        validator: (rule, value, callback) => {
                            if (value == null || value == '' || value == undefined) {
                                callback(' ')
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'change'
                    }],
                    endDate: [{
                        validator: (rule, value, callback) => {
                            if (value == null || value == '' || value == undefined) {
                                callback(' ')
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'change'
                    }],
                    themeAddress: [{
                        required: true,
                        message: '  ',
                        trigger: 'blur'
                    }],
                    preparationDate: [{
                        validator: (rule, value, callback) => {
                            if (value == null || value == '' || value == undefined) {
                                callback(' ')
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'change'
                    }],

                    auditor: [{
                        required: true,
                        message: '  ',
                        trigger: 'change'
                    }],
                    approvedBy: [{
                        required: true,
                        message: '  ',
                        trigger: 'change'
                    }],
                    peportingUnit: [{
                        required: true,
                        message: '  ',
                        trigger: 'change'
                    }],
                    peportingDate: [{
                        validator: (rule, value, callback) => {
                            if (value == null || value == '' || value == undefined) {
                                callback(' ')
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'change'
                    }],
                },
                taskInfo: {
                    viewFlag:true,
                    taskName:""
                }
			}
		},
		mounted: function() {
            if(this.$route.query.close == false){
                this.$http.get(Api.getUserByUserId + this.$route.query.userId)
                .then(function(res){
                    this.user = res.data.data;
                    this.$http.get(Api.getTaskData + "/" + this.$route.query.procinstId + "/" +
                    this.$route.query.taskId+"?close="+this.$route.query.close).then(function(res1){
                        this.taskInfo = res1.data;
                        if(res1.data.viewFlag == false)
                            this.taskInfo.viewFlag = false;
                        else
                            this.taskInfo.viewFlag = true;
                        this.query();
                        return ;
                    })
                })
            }else{
                var search=window.location.href.split('?')[1];//截取URL？后面的参数
                var params={};
                if(search!=""&&search!=undefined){
                　　search.split("&").forEach(
                        function(val){
            　　　　        var arr=val.split("=");
            　　　　      params[arr[0]]=arr[1];
                        }
                    )}
                var code=params.code
                var status = params.status
                if(code != null && code != 'undefine'){
                    this.$http.get(Api.queryToken, {
                        params: {
                            code: code,
                        }
                    }).then(res1 => {
                        if(res1.data.errcode == "1014"){
                             this.$http.get(Api.getReZheng).then(res2=>{
                               window.location.href = decodeURIComponent(res2.bodyText) + "&redirect_uri=" + encodeURIComponent(window.location.href);
                             })
                        }
                        else{
                            this.$http.get(Api.getUserByUserId + this.$route.query.userId)
                            .then(function(res){
                                this.user = res.data.data;
                                this.$http.get(Api.getTaskData + "/" + this.$route.query.procinstId + "/" +
                                this.$route.query.taskId+"?close="+this.$route.query.close).then(function(res1){
                                    this.taskInfo = res1.data;
                                    if(res1.data.viewFlag == false)
                                        this.taskInfo.viewFlag = false;
                                    else
                                        this.taskInfo.viewFlag = true;
                                    this.query();
                                    return ;
                                })
                            })
                        }
                    })
                }
                else{
                    this.$http.get(Api.getReZheng).then(res2=>{
                       window.location.href = decodeURIComponent(res2.bodyText) + "&redirect_uri="+encodeURIComponent(window.location.href);
                    });
                }
            }
        },
		methods: {
            returnTo(){
                if(this.taskInfo.close == true)
                    window.close();
                else
                   this.$router.go(-1);
            },
            routePush(value){
                if (value === '1') {
                    this.showdata.opinion = "同意";
                }else{
                    this.showdata.opinion = null;
                }
            },
            beforeUpload(file) {
                const files = file;
                let formData = new FormData();
                formData.append("file", files);
                this.$http.put(Api.uploadMongoFile, formData).then((res) => {
                    if (res.data.result == "success") {
                        this.showdata.programmeFile = res.data.id;
                        this.fileName = res.data.fileName;
                    } else {
                        this.$Message.error("附件上传失败");
                    }
                }).catch(e => {
                    this.$Message.error("附件上传失败");
                });

                return false;
            },
            setApproveUserName(data) {
                this.showdata.approveUserName = data;
            },
            setApproveUserId(data) {
                this.showdata.approveUserId = data[data.length - 1];
            },

            setApproveUserName1(data) {
                this.showdata.approveUserName = data;
            },
            setApproveUserId1(data) {
                let userId = "";
                for(let i=0;i<data.length;i++){
                    userId += data[i]['value'] + ',';
                }
                this.showdata.approveUserId = userId;
            },
            deleteFile(id) {
                this.$http.delete(Api.uploadMongoFile + "/" + id).then((res) => {
                    console.log(id);
                    if (res.data.result == "success") {
                        this.taskInfo.programmeFile = null;
                        this.fileName = null;

                    }
                }).catch(e => {
                    this.$Message.error("附件上传失败");
                });
            },
            submitAndUpdate(){
                this.$refs['showdata'].validate((valid) => {
                    if (valid) {
                        this.buttonloading1 = true;
                        let data = {};
                        data = {
                            createUserId: this.user.userId,
                            userName: this.user.userName,
                            opinion: this.showdata.opinion,
                            taskId: this.taskInfo.taskId,
                            procinstId: this.taskInfo.procinstId,
                            route: this.showdata.route
                        };
                        this.showdata.updateUserId = this.user.userId
                        this.showdata.updateOrgId = this.user.orgInfo.orgId
                        this.$http.post(Api.updateProgramme, this.showdata).then((res) => {
                            if (res.data.status == '200') {
                                data.route = '1';
                                this.$http.get(Api.taskComplete, {params: data}).then((res) => {
                                    this.buttonloading1 = false;
                                    if (res.data.status == '200') {
                                        this.$Message.success("审批成功")
                                        this.returnTo();
                                    } else {
                                        this.$Message.success("审批失败")
                                    }
                                }).catch(e => {
                                    this.buttonloading1 = false;
                                    this.$Message.error("数据获取失败")
                                })
                            }else{
                                this.buttonloading1 = false;
                            }
                        }).catch(e => {
                            this.buttonloading1 = false;
                            this.$Message.error('请求失败');

                        })
                    }
                })
            },
            query() {
                let url = Api.queryProgrammeById;
                let id = this.taskInfo.workId;
                this.$http.get(url + '/' + id, {params: {}}).then((res) => {
                    this.showdata = res.data.data;
                    this.showdata.startDate = this.formatDate(new Date(this.showdata.startDate), 'yyyy-MM-dd');
                    this.showdata.endDate = this.formatDate(new Date(this.showdata.endDate), 'yyyy-MM-dd');
                    let url = Api.getPTWSchemeFile + "/" + this.showdata.programmeFile;
                    this.$http.get(url).then((res1) => {
                        this.fileId = res1.data.id;
                        this.fileName = res1.data.fileName;
                    }).catch(e => {
                        this.$Message.error("数据获取失败")
                    });


                }).catch(e => {
                    this.$Message.error("数据获取失败")
                })


                // this.$http.get(url + '/' + id, {params: {}}).then((res) => {
                //     this.showdata = res.data.data;
                //     this.showdata.preparationDate = this.formatDate(new Date(this.showdata.preparationDate), 'yyyy-MM-dd');
                //     this.showdata.reportingDate = this.formatDate(new Date(this.showdata.reportingDate), 'yyyy-MM-dd');
                //     this.$http.get(Api.getPTWSchemeFile+"/"+ this.showdata.programmeFile).then((res1) => {
                //         this.$set(this.showdata,"fileId",res1.data.id)
                //         this.$set(this.showdata,"fileName",res1.data.fileName)
                //     }).catch(e => {
                //         this.$Message.error("数据获取失败")
                //     });
                //     if(!this.viewFlag) {
                //         this.$http.get(Api.getProcinstForm + '/' + this.taskInfo.taskId, {params: {}}).then((res) => {
                //             this.formList = res.data.formList;
                //             this.formList.map((i)=>{
                //                 if(i.id == 'route'){
                //                     this.flag = true;
                //                     this.approveList = i.enumData;
                //                 }else if(i.id == 'approver'){
                //                     i.enumData.map((j)=>{{
                //                         if(j.value == 'nextUserId'){
                //                             //单选
                //                             this.approveFlag = '1';
                //                         }else{
                //                             //多选
                //                             this.approveFlag = '2';
                //                         }
                //                     }})
                //                 }
                //             })
                //         }).catch(e => {
                //             this.$Message.error("数据获取失败")
                //         })
                //     }
                // }).catch(e => {
                //     this.$Message.error("数据获取失败")
                // })
            },
            downloadFile(fileId, fileName) {
                let url = this.downloadUrl + "/" + fileId
                this.$http.get(url, {
                    responseType: 'blob' //告诉服务器我们需要的响应格式
                }).then((res) => {
                    console.log(res)
                    const aLink = document.createElement("a");
                    let blob = new Blob([res.data], {
                        type: res.bodyBlob.type //将会被放入到blob中的数组内容的MIME类型
                    });
                    aLink.href = URL.createObjectURL(blob)
                    aLink.download = fileName //标题
                    aLink.click()
                    document.body.appendChild(aLink)
                })
            },
            submit() {
                this.$refs['showdata'].validate((valid) => {
                    if(valid) {
                        this.buttonloading1 = true;
                        let userJson = this.user;
                        let data = {};
                        if(this.formList.length>1)
                        {
                            if(this.formList[1].enumData.value == 'nextUserId'){
                                //单选
                                data = {
                                    createUserId : userJson.userId,
                                    userName : userJson.userName,
                                    opinion : this.showdata.opinion,
                                    taskId : this.taskInfo.taskId,
                                    procinstId : this.taskInfo.procinstId,
                                    route : this.showdata.route,
                                    nextUserId : this.showdata.approveUserId
                                };
                            }else{
                                //多选
                                data = {
                                    createUserId : userJson.userId,
                                    userName : userJson.userName,
                                    opinion : this.showdata.opinion,
                                    taskId : this.taskInfo.taskId,
                                    procinstId : this.taskInfo.procinstId,
                                    route : this.showdata.route,
                                    nextUserIds : this.showdata.approveUserId.substring(0,this.showdata.approveUserId.length-1)
                                };
                            }
                        }else{
                             data = {
                                    createUserId : userJson.userId,
                                    userName : userJson.userName,
                                    opinion : this.showdata.opinion,
                                    taskId : this.taskInfo.taskId,
                                    procinstId : this.taskInfo.procinstId,
                                    route : this.showdata.route
                                };
                        }
                        this.$http.get(Api.taskComplete, {params: data}).then((res) => {
                            this.buttonloading1 = false;
                            console.log(res)
                            if(res.data.status=='200'){
                                this.$Message.success("审批成功")
                                this.returnTo();
                            }else{
                                this.$Message.success("审批失败")
                            }
                        }).catch(e => {
                            this.buttonloading1 = false;
                            this.$Message.error("数据获取失败")
                        })


                    } else {
                        this.$Message.error('请填报完整!');
                    }
                })
            },
            handleCancel() {
                this.showdata = {};
                this.$router.back();
            },
            formatDate(date, fmt) {
                if (/(y+)/.test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
                }
                let o = {
                    'M+': date.getMonth() + 1,
                    'd+': date.getDate(),
                    'h+': date.getHours(),
                    'm+': date.getMinutes(),
                    's+': date.getSeconds()
                };
                for (let k in o) {
                    if (new RegExp(`(${k})`).test(fmt)) {
                        let str = o[k] + '';
                        fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
                    }
                }
                return fmt;
            },
            padLeftZero(str) {
                return ('00' + str).substr(str.length);
            },
        },
	}
</script>
<style lang='css' scoped>
    @import '../../../../index.css';

</style>
